package java_thinking.unit_21.Exercise.barrier;

import java.util.concurrent.CyclicBarrier;

/**
 * @Desc:   1.多个线程互相等待至共同点
 * @author: cww
 * @DateTime: 2019-07-13 16:13
 */

public class CyclicBarrierDemo {

    static class TaskThread extends Thread {
        CyclicBarrier barrier;

        public TaskThread(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(1000);
                System.out.println(getName() + " get in barrier A");
                barrier.await();
                System.out.println(getName() + "break through barrier A");

                Thread.sleep(10);
                System.out.println(getName() + " get in barrier B");
                barrier.await();
                System.out.println(getName() + "break through barrier B");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        int threadNum = 2;
        CyclicBarrier barrier = new CyclicBarrier(threadNum, new Runnable() {
            /**
             * 来执行冲破栅栏代码的线程，是最后一个到达栅栏的线程，见打印日志
             */
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " finished last task");
            }
        });

        for (int i = 0; i < threadNum; i++) {
            new TaskThread(barrier).start();
        }
    }
}
